package net.flowas.genericcrud.model;

import javax.persistence.PostLoad;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;

public class FilePathListener {
  private static final String DOWNLOAD_PREFIX = "rest/crudRest/files/normal/download/";
  private static String basePath;
  public static String getBasePasePath() {
	  if(basePath==null) {
		  return DOWNLOAD_PREFIX;
	  }else {
		  return basePath;
	  }
  }
  public static void setBasePath(String basePath) {
	  FilePathListener.basePath=basePath;
  }
  @PrePersist
  void prePersist(FileInfo info) {
    preSaveOrUpdate(info);
  }

  @PreUpdate
  void preUpdate(FileInfo info) {
    preSaveOrUpdate(info);
  }

  @PostLoad
  void postLoad(FileInfo info) {
    String path = info.getFilePath();
    if (path != null && !info.getFilePath().contains(getBasePasePath())) {
      String filePtah = getBasePasePath() + info.getFilePath();
      info.setFullUrlPath(filePtah);
    }
  }

  private void preSaveOrUpdate(FileInfo info) {
    String path = info.getFilePath();
    if (path != null && path.contains(getBasePasePath())) {
      String filePtah = info.getFilePath().replace(getBasePasePath(), "");
      info.setFilePath(filePtah);
    }
  }
}
